<template>
  <a-modal
    title="修改商户级限额管理"
    v-model="show"
    :maskClosable="false"
    :width="1050"
    placement="right"
    :closable="true"
    @cancel="onClose"
    :footer="null"
    :visiable="merchantLevelManagerEditVisiable"
  >  <a-tabs>
    <a-tab-pane
      key="1"
      tab="商户限额"
    >
    <a-form :form="form">
      <a-row>商户限额</a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="商户号"
                       v-bind="formItemLayout">
            <a-input v-decorator="['mcNo',{rules: [{ required: true, message: '必填字段'}]}]" :disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="日累计限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['dayLimitAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='月累计限额'
                       v-bind="formItemLayout">
            <a-input v-decorator="['monthLimitAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>借记限额</a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="单笔借记限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['singleLimitLoanMaxAmt']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='日累计借记限额'
                       v-bind="formItemLayout">
            <a-input v-decorator="['dayLimitLoanAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="月累计借记限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['monthLimitLoanAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>贷记限额</a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="单笔贷记限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['singleLimitCreditMaxAmt']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='日累计贷记限额'
                       v-bind="formItemLayout">
            <a-input v-decorator="['dayLimitCreditAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="月累计贷记限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['monthLimitCreditAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>退款限额</a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="日累计限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['refundDayLimitAmt']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='单笔借记限额'
                       v-bind="formItemLayout">
            <a-input v-decorator="['reSingleLimitLoanMaxAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="日累计借记限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['refundDayLimitLoanAmt']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='单笔贷记限额'
                       v-bind="formItemLayout">
            <a-input v-decorator="['reSingleLimitCredMaxAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="日累计贷记限额"
                       v-bind="formItemLayout">
            <a-input v-decorator="['refundDayLimitCredAmt']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <br>

    </a-form>

    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
    </a-tab-pane>
    <a-tab-pane
      key="2"
      tab="商户终端限额"
      @change="getTermQuotaList"
    >
      <div :class="advanced ? 'search' : null">
        <!-- 搜索区域 -->
        <a-form layout="horizontal">
          <div :class="advanced ? null: 'fold'">
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="商户号"
                             v-bind="formItemLayout">
                  <a-input v-model="queryParams.mchntNo" :disabled="true"/>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24" v-show="this.instId!=''">
                <a-form-item
                  label="终端编号"
                  :labelCol="{span: 5}"
                  :wrapperCol="{span: 18, offset: 1}">
                  <a-select
                    show-search
                    placeholder="请输入代码或名称"
                    option-filter-prop="children"
                    style="width: 334px"
                    :filter-option="filterOption"
                    @focus="tremSelectMchntNo"
                    @search="tremSelectMchntNo"
                    @change="tremSelected"
                    v-model="queryParams.termNo"
                  >
                    <a-select-option v-for="d in tremSuData" :key="d.termNo">
                      {{ d.termNo }}-{{d.tmName}}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

            </a-row>
          </div>
          <div style="text-align: center;margin-bottom: 20px " v-show="this.instId!=''">
            <a-button type="primary" @click="getTermQuotaList">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetT">重置</a-button>
          </div>
        </a-form>
      </div>
      <div v-show="this.instId!=''">
        <a-table ref="TableInfo"T
                 :columns="columns"
                 :rowKey="
          (record, index) => {
            return index;
          }
        "
                 :dataSource="dataSource"
                 :pagination="pagination"
                 :loading="loading"
                 :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                 :scroll="{ x: 2600 }"
                 @change="handleTableChange">
          <template slot="email" slot-scope="text, record">
            <a-popover placement="topLeft">
              <template slot="content">
                <div>{{text}}</div>
              </template>
              <p style="width: 150px;margin-bottom: 0">{{text}}</p>
            </a-popover>
          </template>
          <template slot="tremMchntInfoOperation" slot-scope="text, record">
            <a-icon v-hasPermission="['merchantLevelManager:edit']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                    @click="editMerchantLevelManager(record)" title="修改"></a-icon>&nbsp;
            <a-icon v-hasPermission="['merchantLevelManager:view']" type="eye" theme="twoTone" twoToneColor="#42b983"
                    @click="infoMerchantLevelManager(record)" title="查看"></a-icon>
            <a-badge v-hasNoPermission="['merchantLevelManager:edit','merchantLevelManager:view']" userStatus="warning" text="无权限"></a-badge>
          </template>
        </a-table>
        <!-- 查看 -->
        <trem-mchnt-info
          ref="tremMchntInfo"
          @close="handleTremMchntInfoClose"
          @success="handleTremMchntInfoSuccess"
          :instId="this.instId"
          :tremMchntInfoVisiable="tremMchntInfo.visiable">
        </trem-mchnt-info>

      </div>
    </a-tab-pane>
    </a-tabs>
  </a-modal>

</template>
<script>
import TremMchntInfo from "./TremMchntInfo";
import {mapState} from "vuex";

  const formItemLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16}
  }
  export default {
    name: 'MerchantLevelManagerEdit',
    components: {TremMchntInfo},
    props: {
      merchantLevelManagerEditVisiable: {
        default: false
      },
      instId: '',
    },
    data() {
      return {
        tremMchntInfo: {
          visiable: false
        },
        advanced: false,
        data: [],
        suData: [],
        tremSuData:[],
        queryParams: {
          instId: '',
          mchntNo: '',
          termNo:''
        },
        dataSource: [],
        selectedRowKeys: [],
        mchntNoLevelInfo: {
          visiable: false
        },
        loading: false,
        formItemLayout,
        form: this.$form.createForm(this),
        validateStatus: '',
        // firstValue: {},
        info: {
          infoName: '',
          remark: '',
          menuId: ''
        },
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
      }
    },

    computed: {
      show: {
        get: function () {
          return this.merchantLevelManagerEditVisiable
        },
        set: function () {
        }
      },
      ...mapState({
        user: state => state.account.user,

      }),
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '终端编号',
          dataIndex: 'termNo',
          scopedSlots: {customRender: 'termNo'},
        },  {
          title: '单笔借记限额(元)',
          dataIndex: 'singleLimitLoanMaxAmt',
          scopedSlots: {customRender: 'singleLimitLoanMaxAmt'},
        }, {
          title: '单笔贷记限额(元)',
          dataIndex: 'singleLimitCreditMaxAmt',
          scopedSlots: {customRender: 'singleLimitCreditMaxAmt'},
        },{
          title: '日累计借记限额(元)',
          dataIndex: 'dayLimitLoanAmt',
          scopedSlots: {customRender: 'dayLimitLoanAmt'},
        }, {
          title: '日累计贷记限额(元)',
          dataIndex: 'dayLimitCreditAmt',
          scopedSlots: {customRender: 'dayLimitCreditAmt'},
        }, {
          title: '月累计借记限额(元)',
          dataIndex: 'monthLimitLoanAmt',
          scopedSlots: {customRender: 'monthLimitLoanAmt'},
        }, {
          title: '月累计贷记限额(元)',
          dataIndex: 'monthLimitCreditAmt',
          scopedSlots: {customRender: 'monthLimitCreditAmt'},
        }, {
          title: '日累计限额',
          dataIndex: 'dayLimitAmt',
          scopedSlots: {customRender: 'dayLimitAmt'},
        }, {
          title: '月累计限额',
          dataIndex: 'monthLimitAmt',
          scopedSlots: {customRender: 'monthLimitAmt'},
        }, {
          title: '操作',
          dataIndex: 'tremMchntInfoOperation',
          fixed: 'right',
          scopedSlots: {customRender: 'tremMchntInfoOperation'}
        }]
      },
    },
    mounted() {
    },
    //监听
    watch: {
      tabActiveKey (val, oldVal) {
        this.$nextTick(() => {
          switch (val) {
            case this.tremMchntInfo.visiable==false:
              this.getTermQuotaList();
              break;
          }
        })
      }
    },
    methods: {
      handleTremMchntInfoClose() {
        this.tremMchntInfo.visiable = false
        this.getTermQuotaList()
      },
      tremSelected(val) {
        this.tremSelectMchntNo(val)
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      tremSelectMchntNo(val) {
        let mchntNo = this.queryParams.mchntNo

        if (mchntNo) {
          this.tremSuData = []
          let param = {}
          if (val) {
            param = {
              q: encodeURIComponent(val + `&${this.instId}`),
              pageSize: 20,
              mcNo : mchntNo,
              opp: '0'
            }

            if (val.length >= 5) {
              this.$get('/admin/quota/merchantLevelManager/getAddTermNoList', param).then((r) => {
                let result = r.data.data
                this.tremSuData=result;
              })
            }
          } else {
            param = {
              q: encodeURIComponent(`&${this.instId}`),
              pageSize: 20,
              mcNo : mchntNo,
              opp: '0'
            }
            this.$get('/admin/quota/merchantLevelManager/getAddTermNoList', param).then((r) => {
              let result = r.data.data
              this.tremSuData=result;
            })
          }
        }else {
          this.$message.warning('请先选择商户号获取终端编码！')
        }},
      editMerchantLevelManager(record) {
     record.mchntNo=this.queryParams.mchntNo;
     record.operatorType='edit',
          this.$refs.tremMchntInfo.setInfoFieldsTremValues(record)
          this.tremMchntInfo.visiable = true
      },
      infoMerchantLevelManager(record) {
        record.mchntNo=this.queryParams.mchntNo;
        record.operatorType='info',
          this.$refs.tremMchntInfo.setInfoFieldsTremValues(record)
        this.tremMchntInfo.visiable = true
      },
      handleTableChange(pagination, filters, sorter) {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        this.filteredInfo = filters
        this.sortedInfo = sorter
        // this.userInfo.visiable = false

        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      handleTremMchntInfoSuccess() {
        this.tremMchntInfo.visiable = false
        this.getTermQuotaList()
        this.$message.success('修改成功')
        this.search()
      },
      search() {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        let {sortedInfo, filteredInfo} = this
        let sortField, sortOrder
        // 获取当前列的排序和列的过滤规则
        if (sortedInfo) {
          sortField = sortedInfo.field
          sortOrder = sortedInfo.order
        }
        let params = this.queryParams

        this.fetch({
          sortField: sortField,
          sortOrder: sortOrder,
          ...params,
          ...filteredInfo
        })
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },

      reset() {
        this.loading = false
        this.form.resetFields()
      },
      resetT(){
        this.tremSuData=[]
        this.queryParams.termNo=''
      },
      onClose() {
        this.reset()
        this.$emit('close')
      },
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.setInfoFields()
            this.loading = true
            this.info.instId = this.instId
            this.info.optFlag = 'upd'
            this.info.notDiffAcctId=this.suData.notDiffAcctId
            this.info.creditId=this.suData.creditId
            this.info.loanId=this.suData.loanId
            this.info.refundNotDiffAcctId=this.suData.refundNotDiffAcctId
            this.info.refundCreditId=this.suData.refundCreditId
            this.info.refundLoanId=this.suData.refundLoanId
            const params = {};
            Object.assign(params, this.info, {
              optFlag: "upd",
            });
            this.$put('/admin/quota/merchantLevelManager/editMcQuota',
             params
            ).then((r) => {
              if(r.data.code!='100000'){
                this.reset();
                this.loading = false
                this.$message.error(r.data.message)
              }else {
                this.reset()
                this.$emit('success')
              }
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
async getTermQuotaList(params = {}){
  this.loading = true
  if (this.paginationInfo) {
    // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
    this.$refs.TableInfo.pagination.current = this.paginationInfo.current
    this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
    params.pageSize = this.paginationInfo.pageSize
    params.pageNum = this.paginationInfo.current
    params.instId=this.instId
    params.mcNo=this.queryParams.mchntNo
  } else {
    // 如果分页信息为空，则设置为默认值
    params.pageSize = this.pagination.defaultPageSize
    params.pageNum = this.pagination.defaultCurrent
    params.instId=this.instId
    params.mcNo=this.queryParams.mchntNo
  }

  this.$get('/admin/quota/merchantLevelManager/getTermQuotaList',
    params,{
    instId: this.instId,
      mcNo: this.queryParams.mchntNo
    }).then((r) => {

      this.dataSource=r.data.content
      const pagination = {...this.pagination}
      this.pagination = pagination
      this.loading = false
  }).catch(() => {
    this.loading = false
  })
},
      setInfoFields() {
        let values = this.form.getFieldsValue(['mcNo', 'dayLimitAmt', 'monthLimitAmt', 'singleLimitLoanMaxAmt',
          'dayLimitLoanAmt', 'monthLimitLoanAmt', 'singleLimitCreditMaxAmt', 'dayLimitCreditAmt',
          'monthLimitCreditAmt', 'refundDayLimitAmt', 'reSingleLimitLoanMaxAmt', 'refundDayLimitLoanAmt',
          'reSingleLimitCredMaxAmt', 'refundDayLimitCredAmt','notDiffAcctId',
          'creditId','loanId','refundNotDiffAcctId','refundCreditId','refundLoanId'])
        if (typeof values !== 'undefined') {
          Object.keys(values).forEach(_key => {
            this.info[_key] = values[_key]
          })
        }
      },

      setMerchantLevelManagerFormValues ({...info}) {
        let fields = ['mcNo', 'dayLimitAmt', 'monthLimitAmt', 'singleLimitLoanMaxAmt', 'dayLimitLoanAmt',
          'monthLimitLoanAmt', 'singleLimitCreditMaxAmt', 'dayLimitCreditAmt', 'monthLimitCreditAmt', 'refundDayLimitAmt',
          'reSingleLimitLoanMaxAmt', 'refundDayLimitLoanAmt', 'reSingleLimitCredMaxAmt', 'refundDayLimitCredAmt','notDiffAcctId',
          'creditId','loanId','refundNotDiffAcctId','refundCreditId','refundLoanId']
        Object.keys(info).forEach((key) => {
          if (fields.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = info[key]
            if (key=='mcNo'){
              this.queryParams.mchntNo=  obj.mcNo
            }
            this.form.setFieldsValue(obj)
          }
        })
        this.suData=info;
      },


    },

  }
</script>

